package org.linkerproject.browser;

import org.eclipse.swt.widgets.Shell;
import org.linkerproject.server.LocalServer;
import org.linkerproject.server.RefreshEvent;
import org.linkerproject.server.RefreshListener;

public class BrowserManager {

	private LocalServer localServer;

	private BrowserWindow browserWindow;

	private String path;

	private Shell shell;

	public BrowserManager(Shell shell, String path, LocalServer localServer) {
		this.path = path + "/http/";
		this.shell = shell;
		this.localServer = localServer;
		localServer.addRefreshListener(new RefreshListener() {

			@Override
			public void refresh(RefreshEvent e) {
				BrowserManager.this.refresh();
			}
		});

		// operateWindow = new OperateWindow(shell, this);
		browserWindow = new BrowserWindow(shell, this);
		this.gotoIndex();
	}

	public void browse(String url) {
		if (url.startsWith("file:")) {
			this.localView(url.substring(5));
		}
		browserWindow.browse(url);
	}

	public void browseLocal(String file) {
		this.browse(path + file);
	}

	public void findDialog() {
		SearchDialog dialog = new SearchDialog(shell, this);
		dialog.open();
	}

	public String getTitle() {
		return browserWindow.getTitle();
	}

	public void gotoDialog() {
		UrlDialog dialog = new UrlDialog(shell, this);
		dialog.open();
	}

	public void gotoIndex() {
		this.browse("file:" + path + "index.html");
	}

	public void localView(String url) {
		localServer.view(url);
	}

	public void refresh() {
		browserWindow.refresh();
	}

	public void save(String lastUrl, String html) {

		localServer.save(lastUrl, html);

	}

}
